<template>
  <div class="welcome">
    <img class="logo anim-fadeIn" :src="logo">
    <p v-if="!isWX">请在微信浏览器打开</p>
  </div>
</template>

<script>
  import logo from './img/loading.gif'
  export default {
    name: 'authorize',
    data () {
      return {
        logo: logo,
        isWX: true,
        title:'卡库回收'
      }
    },
    methods: {
      login(){
        this.axios.post('/api/Weixin/getTicket',{
          url: window.location.href.split('#')[0]
        }).then((res)=>{
          let data = res.data
          wx.config({
            debug: false,
            appId: data.appId,
            timestamp: data.timestamp,
            nonceStr: `${data.nonceStr}`,
            signature: data.signature,
            jsApiList: []
          })
          wx.ready((res) => {
            let url = encodeURIComponent(window.location.href.split('#')[0])
            let urls = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+data.appId+'&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
            let code = this.getUrlParam("code")
            if(!code){
              window.location = urls
            }else{
              this.$store.commit('code',code)
              wx.hideAllNonBaseMenuItem();
              this.axios.get('/home/Login/getInfo?code='+code).then((res)=>{
                if(res.data.code==200){
                  this.$store.commit('token',res.data.data)
//                  console.log(this.$store.state.token)
                  this.$router.push('/index')
                }
              })
            }
          })
        })
      },
      getUrlParam(name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
      }
    },
    created () {
      this.setTitle(this.title)
//      console.log(window.location.href)
      let ua = window.navigator.userAgent.toLowerCase()
      if (ua.indexOf('micromessenger') === -1) {
        // 不是微信环境
//        console.log('不是微信环境')
        this.isWX = false
        return
      }
      this.login()
//      this.isWX = true
//      console.log('***')
//      console.log(this.$store.state.code)
//      this.$router.push('/index')
    }
  }
</script>

<style scoped>
  .welcome{
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: rgb(251, 251, 251);
    font-size: 16px;
    text-align: center;
    color: #999;
  }
  .logo{
    display: block;
    margin: 0 auto;
    padding-top: 70%;
    width: 50%;
  }
</style>

